import React, { memo, useEffect, useRef } from 'react';
import { shallowEqual } from 'react-redux';
import { useSelector } from 'react-redux';

import { scrollTo } from "@/utils/ui-helper";

import { LyricWrapper } from "./style";

const PanelLyric = memo(() => {
  const lrcPanelRef = useRef();
  const { lyricList, lyricIndex } = useSelector(state => ({
    lyricList: state.getIn(["player", "lyricList"]),
    lyricIndex: state.getIn(["player", "lyricIndex"])
  }), shallowEqual);

  const addClassName = (index) => {
    let cName = "lrc-item";
    if (lyricIndex === index) {
      cName += " active";
    };
    return cName;
  };

  useEffect(() => {
    if (lyricIndex > 0 && lyricIndex < 3) return;
    scrollTo(lrcPanelRef.current, (lyricIndex - 3) * 32, 300);
  }, [lyricIndex])
  
  return (
    <LyricWrapper ref={lrcPanelRef}>
      <div className="lrc-content">
        {
          lyricList.map((item, index) => {
            return (
              <div 
                key={item.time}
                className={addClassName(index)}
              >
                { item.content }
              </div>
            )
          })
        }
      </div>
    </LyricWrapper>
  )
})

export default PanelLyric